<template>
  <div ref="split" class="split">
    <div ref="leftView" class="left-view">
      <LeftTree ref="leftTreeRef" v-model:current="currentCase" v-model:status="adjustStatus"
        :currentKey="currentKey" />
    </div>
    <div ref="rightView" class="right-view">
      <div class="right-ct">
        <div class="tit">
          <span>{{ currentCase.name }}</span>
        </div>
        <div :class="`r-ct ${currentKey}`">
          <div ref="chartTable" class="chart-table">
            <div ref="chartBox" class="chart-box" v-loading="chartLoading">
              <ChartView ref="chartView" class="chart-view" :currentKey="currentKey"></ChartView>
            </div>
            <div ref="tableBox" class="table-box" :style="`margin-top: ${isEdit ? 38 : 0}px`">
              <TableBox ref="tableBoxRef" :data="chartData" :current="currentCase" :isEdit="isEdit"
                :loading="chartLoading" @update="getChartData" @updateChart="updateChart"></TableBox>
            </div>
          </div>
          <div ref="paramsBox" class="params-box">
            <ParamsView ref="paramsView" class="params-view" :current="currentCase" :currentKey="currentKey">
            </ParamsView>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, computed, getCurrentInstance, watch } from "vue";
import LeftTree from "./components/LeftTree/index.vue";
import ChartView from "./components/ChartView.vue";
import ParamsView from "./components/ParamsView.vue";
import TableBox from "./components/TableBox.vue";
import Split from "split.js";
import type { TreeItem, ResultItem } from "@/api/adjust/index.d";
import { apiMap, type TypeKeys } from "./index";

import { inject } from 'vue';
import { SEND_CALIB_CMD_KEY } from '../types';
import { useCalibStore } from "../store/calibStore";

// 1. 获取平台注入的 sendCalibCmd（根组件在作用域内，可正常获取）
const sendCalibCmd = inject(SEND_CALIB_CMD_KEY);
// 2. 实例化组合式 store
const calibStore = useCalibStore();


if (!sendCalibCmd) {
  console.error("插件根组件未获取到 sendCalibCmd，初始化失败");
  // return;
}
console.log("插件根组件获取到 sendCalibCmd，初始化成功", sendCalibCmd, calibStore.sendCalibCmd); // 先确认这个值是否为函数

// 修复参数错误：直接传递 { sendCalibCmd } 而不是 { injections: sendCalibCmd }
if (!calibStore.sendCalibCmd) {
  console.log("Pinia 中未存储 sendCalibCmd，进行存储");
  calibStore.setInjections({ sendCalibCmd } as any);
}

// 验证存储结果
console.log("存储后 Pinia 中的值：", calibStore.sendCalibCmd);

defineOptions({
  name: "AdjustList"
});
const leftTreeRef = ref<InstanceType<typeof LeftTree>>(); // 左侧树
const chartView = ref<InstanceType<typeof ChartView>>(); // 折线图
const tableBoxRef = ref<InstanceType<typeof TableBox>>(); // 表格
const paramsView = ref<InstanceType<typeof ParamsView>>(); // 参数

const currentKey = computed(() => currentCase.value.pId || (currentCase.value.id as TypeKeys));
const isEdit = computed(() => {
  const { children, pId } = currentCase.value;
  return !(children || ["lineinfo", "positioninfo"].includes(pId!!));
}); // 表格是否可新增

const chartData = ref<ResultItem[]>([]);
const chartLoading = ref(false);
const currentCase = ref<Partial<TreeItem>>({}); // 当前选中的校准项
const adjustStatus = ref(1); // 校准状态 1:初始状态 2：校准中

watch(
  () => currentCase.value.id,
  () => {
    if (currentCase.value.children) {
      chartData.value = [];
    } else {
      getChartData();
    }
  }
);
watch(adjustStatus, (_, oldVal) => {
  if (oldVal === 1) {
    chartData.value = [];
  }
});
onMounted(() => {
  initSplit();
});
const initSplit = () => {
  const { leftView, rightView, chartTable, paramsBox, chartBox, tableBox, chartView } = getCurrentInstance()?.refs || {};
  const options = [
    { el: [leftView, rightView], direction: "horizontal", sizes: [13, 87] },
    { el: [chartBox, tableBox], direction: "vertical", sizes: [60, 40], minSize: [50, 50] },
    { el: [chartTable, paramsBox], direction: "horizontal", sizes: [70, 30], minSize: [50, 50] }
  ];
  options.forEach((x: any) => {
    Split(x.el, {
      snapOffset: 0,
      gutterSize: 10,
      onDrag: () => {
        (chartView as typeof ChartView)?.chartResize();
      },
      ...x
    });
  });
};
/**
 * @description: 更新折线图
 * @return {*}
 */
const updateChart = () => {
  chartView.value?.drawChart(chartData.value);
};
/**
 * @description: 获取结果数据
 * @return {*}
 */
const getChartData = async () => {
  const { resultList, resultListKey } = apiMap[currentKey.value];
  chartLoading.value = true;
  const { data } = await resultList(
    {
      [resultListKey]: currentCase.value.id || ""
    } as { freqScopeId: string } & { antennaFactorId: string } & { lineId: string } & { positionId: string },
    { calibrationName: "开场校准管理器" }
  );
  chartLoading.value = false;
  chartData.value = data || [];
  updateChart();
};
</script>
<style scoped lang="scss">
.split {
  display: flex;
  height: 100%;
  color: #333333;
  overflow: hidden;
  font-size: 12px;
  background: #fff;

  .left-view {
    background-color: #f3f3f3;
    height: 100%;
    min-width: 180px;
  }

  .right-view {
    background: #fff;
    overflow: hidden;

    .right-ct {
      margin: 10px 10px 10px 0;
      border: 1px solid #eaeaea;
      height: calc(100% - 20px);
    }

    .tit {
      padding: 0 16px;
      font-weight: bold;
      height: 38px;
      line-height: 38px;
      background-color: #f4f4f4;
      border-bottom: 1px solid #eaeaea;
    }

    .r-ct {
      display: flex;
      height: calc(100% - 59px);
      margin: 10px;
      position: relative;

      &.freqscope {
        .chart-table {
          .chart-box {
            display: none;
          }
        }

        :deep(.gutter) {
          display: none;
        }

        .params-box {
          display: none;
        }
      }

      &.antennafactor {
        .chart-table {
          flex-direction: row-reverse;

          .chart-box {
            width: 50%;
            height: 100% !important;
          }
        }

        :deep(.gutter-horizontal) {
          display: none;
        }

        .params-box {
          display: none;
        }
      }

      .chart-table {
        display: flex;
        flex-direction: column;
        flex: 1;

        .chart-box {
          border: 1px solid #eaeaea;
          box-sizing: border-box;
        }

        .table-box {
          flex: 1;
          margin-top: 38px;
          overflow: hidden;

          :deep(.xc-table) {
            .xc-table-editable-add {
              position: absolute;
              top: 0;
              left: 0;
              margin: 0;
              border: none;
              background-color: transparent;
              height: 38px;
              width: 60px;
              // svg {
              //   display: none;
              // }
            }
          }
        }
      }
    }
  }
}

:deep(.gutter) {
  background-repeat: no-repeat;
  background-position: 50%;
  height: 100%;
  background-color: transparent;
  min-width: 10px;
}
</style>
